<template>
  <div style="padding: 16px;">
    <t-page-header title="模板列表" />

    <t-row :gutter="16">
      <t-col :span="4" v-for="tpl in templates" :key="tpl.id">
        <t-card
          :title="tpl.type + ' 模板'"
          :cover="tpl.cover"
          bordered
          hover-shadow
          style="margin-bottom: 16px; cursor: pointer;"
        >
          <template #description>
            更新时间：{{ tpl.updateTime }}
          </template>

          <template #actions>
            <t-button size="small" theme="primary" @click="printJson(tpl)">编辑</t-button>
            <t-button size="small" variant="text" @click="previewImage(tpl.cover)">预览</t-button>
          </template>
        </t-card>
      </t-col>
    </t-row>

    <t-dialog
      v-model:visible="showPreview"
      header="模板封面预览"
      width="80%"
      confirm-btn="关闭"
      :onConfirm="onClose"
      :footer="false"
    >
      <img :src="previewSrc" style="width: 100%;" />
    </t-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { MessagePlugin } from 'tdesign-vue-next'
import axios from 'axios'

const templates = ref([])
const showPreview = ref(false)
const previewSrc = ref('')
const router = useRouter()
const UPLOAD_PREFIX = 'http://localhost:8080/uploads/'

onMounted(async () => {
  try {
    const res = await axios.get('http://localhost:8080/data/template')
    if (Array.isArray(res.data)) {
      templates.value = res.data.map(tpl => ({
        ...tpl,
        cover: tpl.cover.startsWith('http') ? tpl.cover : UPLOAD_PREFIX + tpl.cover
      }))
    }
  } catch (e) {
    console.error('获取模板列表失败', e)
    MessagePlugin.error('模板加载失败')
  }
})

const previewImage = (src) => {
  previewSrc.value = src
  showPreview.value = true
}

const onClose = () => {
  showPreview.value = false
}

const printJson = (tpl) => {
  try {
    const jsonStr = encodeURIComponent(tpl.json)
    router.push({
      path: '/',
      query: { data: jsonStr, tempId: tpl.id }
    })
  } catch (e) {
    console.error('JSON解析失败', e)
    MessagePlugin.warning('JSON 格式错误')
  }
}
</script>
